<template>
  <el-input
    ref="roadInput"
    v-model="inputValue"
    class="road-input"
    clearable
    placeholder="K0000+000.00"
    :title="inputValue ? inputValue : 'K0000+000.00'"
    @blur="blur"
    @clear="clear" />
</template>
<script>
export default {
  name: 'RoadInput',
  props: {
    value: [String, Number]
  },
  data() {
    return {
      inputValue: ''
    }
  },
  watch: {
    value: {
      handler(val) {
        this.inputValue = this.formatValue(val)
      },
      immediate: true
    }
  },
  // created() {
  //   this.inputValue = this.formatValue(this.value)
  // },
  methods: {
    blur() {
      this.inputValue = this.formatValue(this.inputValue)
      // 将值转换为数字  提交到后台
      this.$emit('input', this.inputValue.replace(/\./, '').replace(/K/ig, '').replace(/\+/, '.'))
      this.$emit('blur', this.antiFormatValue(this.inputValue))
      // console.log('blur')
    },
    /**
     * 格式化展示的值
     */
    formatValue(val) {
      if (!val && val !== 0) return ''
      let value = val.toString().toUpperCase()
      if (value.startsWith('-K') || value.startsWith('K')) {
        value = value.includes('+') ? value : value.replace(/\./g, '+')
      } else if (value.startsWith('-')) {
        value = '-K' + (value.includes('+') ? value : value.slice(1).replace(/\./g, '+'))
      } else {
        value = 'K' + (value.includes('+') ? value : value.replace(/\./g, '+'))
      }
      if (value.includes('+')) {
        const int = value.slice(0, value.indexOf('+'))
        const decimal = value.slice(value.indexOf('+') + 1)
        if (decimal.includes('.')) {
          value = int + '+' + decimal
        } else {
          value = int +
                  '+' +
                  (decimal.length <= 3 ? decimal + '0'.repeat(3 - decimal.length) : decimal.slice(0, 3)) +
                  '.' +
                  (decimal.length <= 3 ? '00' : decimal.slice(3) + '0'.repeat(5 - decimal.length > 0 ? 5 - decimal.length : 0))
        }
      } else {
        value = value + '+000.00'
      }
      return value
    },
    antiFormatValue(valueStr) { // 反格式化
      let result = valueStr + ''
      if (result.indexOf('K') > -1) {
        result = result.replace('K', '')
      }
      if (result.indexOf('+') > -1 && result.indexOf('.') > -1) {
        result = result.replace('.', '')
        result = result.replace('+', '.')
      }
      return result
    },
    clear() {
      this.$emit('input', '')
      this.$emit('blur')
      // this.$refs.roadInput.focus()
    }
  }
}
</script>
